<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>长连接</title>
</head>
<body>
<form onsubmit="return false">
    <script>
   var socket;
   //判断当前浏览器是否支持socket编程
        if(window.WebSocket)
        {
            socket=new WebSocket("ws://localhost:7000/hello");
            //这个相当于channel，ev是收到服务器端消息
            socket.onmessage=function (ev) {
              var rt=  document.getElementById("respText");
              rt.value=rt.value+"\n"+ev.data;
            }
            //相当于连接开启
            socket.onopen=function (ev) {
                var rt=  document.getElementById("respText");
                rt.value=rt.value+"\n"+"连接服务器成功";
            }
            socket.onclose=function (ev) {
                var rt=  document.getElementById("respText");
                rt.value=rt.value+"\n"+"连接断开";
            }
            

        }
        else {
            alert("当前浏览器不支持socket");
        }
        //发送消息到服务器
        function send(message) {
            //先判断webSocket是否创建完成
            if(!window.socket)
            {
                var rt=  document.getElementById("respText");
                rt.value=rt.value+"\n"+"你还未连接上服务器";
            }
            if(socket.readyState==WebSocket.OPEN)
            {
                //通过socket发送消息
                socket.send(message);
            }
            else {
                var rt=  document.getElementById("respText");
                rt.value=rt.value+"\n"+"你还未连接上服务器";
            }
        }
    </script>
<textarea style="width: 300px;height: 300px" name="msg" ></textarea>
    <button onclick="send(this.form.msg.value)" type="button"  >发送</button>
    <textarea id="respText" style="width: 300px;height: 300px" ></textarea>
    <button type="button" onclick="document.getElementById('respText').value=''" >清空</button>
</form>
</body>
</html>